#!/usr/bin/env bash
# Dark Factory post-commit hook — runs the local critic against the
# just-made commit. Uses your subscription-backed CLIs (Cursor / Codex /
# Claude / Grok) instead of pay-per-token API keys, so cost is flat-rate
# regardless of commit cadence.
#
# Implements the consumer-shape adoption pattern documented in
# `@momentiq/dark-factory-cli` README and `momentiq-ai/dark-factory`
# `docs/CONSUMER-ADOPTION.md` § 3. Replaces the previous embedded
# `tools/agent-review/` shim shipped through sage-blueprint BP-10
# (see BP-N Dark-Factory-Consumer cycle).
#
# Escape hatches:
#   AGENT_REVIEW_SKIP=1 git commit -m "..."  # one-commit local skip
#   AGENT_REVIEW_BYPASS="<reason>" git push  # policy bypass on pre-push
#
# Behavior:
#   - Captures SHA at hook time (NOT in the background process). If two
#     commits land before the background process starts, the literal
#     "HEAD" would resolve to the SECOND commit and the first would
#     never get an artifact -- pre-push would then block on missing
#     review for the first SHA.
#   - Detached background invocation so the commit returns immediately.
#   - Pins the `local` profile so the critic uses subscription auth
#     paths declared in `.agent-review/config.json:profiles.local.auth`.

set -euo pipefail

if [[ "${AGENT_REVIEW_SKIP:-}" == "1" ]]; then
  echo "df: review skipped by AGENT_REVIEW_SKIP=1"
  exit 0
fi

CLI="./node_modules/.bin/df"
if [[ ! -x "${CLI}" ]]; then
  echo "df: CLI not installed at ${CLI} -- run 'npm install' first (skipping post-commit)" >&2
  exit 0   # don't block commits; just warn
fi

SHA="$(git rev-parse HEAD)"
COMMON_DIR="$(git rev-parse --git-common-dir 2>/dev/null || echo .git)"
mkdir -p "${COMMON_DIR}/agent-reviews"
LOG_FILE="${COMMON_DIR}/agent-reviews/post-commit.log"

# Detached background invocation -- commit returns immediately.
# `AGENT_REVIEW_PROFILE=local` selects the subscription-auth aggregation
# profile in .agent-review/config.json. The variable is exported only to
# the background subprocess; it does not pollute the interactive shell.
AGENT_REVIEW_PROFILE=local nohup "${CLI}" review --commit "${SHA}" \
  >"${LOG_FILE}" 2>&1 \
  </dev/null &
disown || true

echo "df: review started for ${SHA:0:12} (log: ${LOG_FILE})"
echo "df: inspect with 'npx df status --commit ${SHA:0:12}' once it finishes"
